import { request } from '../utils/request';

export interface JacgDbTableDetailItem {
  id: number;
  unitId: string;
  tableName: string;
  // operation from backend (lowercase like select/insert), prefer using operationType for display
  operation?: string;
  operationType?: string;
  mapperClassName?: string;
  mapperMethodName?: string;
  methodFullName?: string; // backward compatibility
  sqlStatement?: string;
  xmlFileName?: string;
  xmlFilePath?: string;
  tableSeq?: number;
  mapperSimpleClassName?: string;
  createTime?: string;
  methodStartLine?: number;
  methodEndLine?: number;
  sourceType?: string; // MYBATIS_XML, MYBATIS_ANNOTATION, JPA, NATIVE
}

export interface PageResult<T> {
  records: T[];
  total: number;
  size: number;
  current: number;
}

export interface JacgDbTableQuery {
  pageNum?: number;
  pageSize?: number;
  keyword?: string;
  tableName?: string;
  operationType?: string;
}

export interface TableUsageSummary {
  tableName: string;
  usageCount: number;
}

export async function fetchJacgDbTablePage(unitId: string, data: JacgDbTableQuery) {
  return request({
    url: `/unit/${unitId}/database/jacg/pageQuery`,
    method: 'post',
    data
  });
}

export async function fetchDistinctTables(unitId: string, keyword?: string) {
  return request({
    url: `/unit/${unitId}/database/tables`,
    method: 'get',
    params: keyword ? { keyword } : undefined
  });
}

export interface TableSummary {
  tableName: string;
  operationTypes: string[];
  operationCount: number;
  sourceTypes: string[];
}

export interface TableSummaryQuery {
  pageNum?: number;
  pageSize?: number;
  keyword?: string;
  operationType?: string;
}

export async function fetchTableSummaryPage(unitId: string, params: TableSummaryQuery) {
  return request({
    url: `/unit/${unitId}/database/tables/page`,
    method: 'get',
    params
  });
}

export async function fetchTableOperations(unitId: string, tableName: string, params: {
  pageNum?: number;
  pageSize?: number;
  operationType?: string;
}) {
  return request({
    url: `/unit/${unitId}/database/tables/${encodeURIComponent(tableName)}/operations`,
    method: 'get',
    params
  });
}
